var entries = Array();
var numberOfBoxes =0;
var index = 1;
var oldSupplierID = null; 

$(document).ready(function() 
{ 
            $(".informationTable").on("click", " tr td", addInput);
            $('#name').on("click", addInput);
            $(document).on("click", ".deleteInput" ,deleteInput);           
});

function addInput()
{   
  if((typeof($(this).attr('name')) != 'undefined') && ($('input[name="'+$(this).attr('name')+'"]').length < 1))  // If a InputElement already exists do nothing
  {
      var text = $(this).text();                    //saves the actuall content 
      if("roomShould" === $(this).attr('name'))     //Select if the RooomShould Element is the event (select Box) 
      {
          if($('select[name="'+$(this).attr('name')+'"]').length < 1)
          {
                entries[$(this).attr('name')] = text;
                var name = $(this).attr('name');
                var element = $(this);
                $(this).empty();
                $(this).append('<img src="../design/pictures/status_anim.gif" width="45px" />');
                $.post("ajax/getRooms.php").done(function(data)
                {
                    element.empty();                                
                    var roomsAndNumbers = data.split(";");
                    element.append($("<select>").attr({"name":"roomShould"}).append(function()
                    {
                        for (var i=0;i<roomsAndNumbers.length-1;i++)
                        { 
                            temp = roomsAndNumbers[i].split(",");
                            $(this).append($("<option>").attr({"value":temp[1]}).text(temp[0]));
                        }    
                    }));

                    element.append($("<input>").attr({"type":"Button", "value":"Abbruch", "name":"abort", "class":"deleteInput"}));
                    if(numberOfBoxes===0)
                       {
                           $('#submitArea').append($('<input>').attr({"type":"submit", "value":"Übernehmen", "name":"submit"}));
                       }
                    numberOfBoxes++;
                }); 
            }
      }else                           
      {
        entries[$(this).attr('name')] = text;       //saves the content of the element in entries
        var name = $(this).attr('name');            //get the name of the element 
        $(this).text('');                           //delete the contetn of the element
        $(this).append($("<input>").attr({"name":name, "type":"text", "value":text}))   //insert an input element and an button
                .append($("<input>").attr({"type":"Button", "value":"Abbruch", "name":"abort", "class":"deleteInput"}));
        if(numberOfBoxes===0)                       //if the first input element add the commit button
        {
            $('#submitArea').append($('<input>').attr({"type":"submit", "value":"Übernehmen", "name":"submit"}));
        }
        numberOfBoxes++;
      }
   }            
}

function deleteInput()
{   
            $(this).prev().replaceWith(entries[$(this).prev().attr('name')]);
            $(this).remove();
            numberOfBoxes--;
            if(numberOfBoxes === 0)
             {
               $('#submitArea').empty();
             }
}
  

function ToggleTable(table)
{
    $('.'+table).toggle();

}


function deleteDevice(tag, id)
{
  if(confirm("Wollen Sie dieses Gerät wirklich löschen?"))
  {
   tag.src = "../design/pictures/loading.gif";
   $.post("ajax/devicesDelete.php",{"deviceID":id}).done(function(data)
   {
     if(data==="true")
     {document.location="devices.php";}
   });   
  }
}

function deleteAddition(td ,additionID, deviceID)
{
  if(confirm("Diese Zusatzinformation löschen?"))
  {
   td.innerHTML='<img src="../design/pictures/loading.gif" width="20px" alt="..." />';
   $.post("ajax/additionDelete.php",{deviceID:deviceID, additionID:additionID}).done(function(data)
   {
     if(data==="true")
     {$(td).closest('tr').fadeTo(400,0,function(){$(this).remove();});}
   });   
  }
}

function changeAdditionInputField(input)
{
  var check= true; 
  for (var i=0;i < index ;i++)
  {
    var tempTyp = $(document.getElementById('additionTyp'+(i)));
    var tempValue = $(document.getElementById('additionValue'+(i)));
    var tempDate = $(document.getElementById('additionDate'+(i)));
    if(tempTyp.val() === "" || tempValue.val() === "" || tempDate.val() ==="")
    {
        check = false;
    }
  }
  
  var $textfield=$(input);
  if(check)
  {
    if($textfield.closest('tr').next('.line').length <= 0)
    {
       var date = new Date();
      $textfield.closest('tr').after('<tr><td><input list="additionTyps" type="text" id="additionTyp'+index+'" name="addition['+index+'][0]" onchange="changeAdditionInputField(this)" size="20px\" /></td><td><textarea rows="1" cols="20" id="additionValue'+index+'" name="addition['+index+'][1]"  onchange="changeAdditionInputField(this)"  size="20px"/></td><td><input type="datetime-local" value="'+ date.format("yyyy-mm-dd")+'T'+date.format("HH:MM:ss")+'" id="additionDate'+index+'" name="addition['+index+'][2]"  onchange="changeAdditionInputField(this)" size="20px"/></td><td></td></tr>');    
      index++;
    }
  }
  if(!check)
  {
     var id;
     if ($textfield.attr('id').match('additionTyp'))
        {
          id = $textfield.attr('id').replace('additionTyp','');
        }
     if ($textfield.attr('id').match('additionValue'))
        {
          id = $textfield.attr('id').replace('additionValue','');
        }
     if ($textfield.attr('id').match('additionDate'))
        {
          id = $textfield.attr('id').replace('additionDate','');
        }
    var tempTyp = $(document.getElementById('additionTyp'+(id)));
    var tempValue = $(document.getElementById('additionValue'+(id)));
    var tempDate = $(document.getElementById('additionDate'+(id)));
    if((tempTyp.val() === "" && tempValue.val() === "" && tempDate.val() ==="") && id > 0)
    {
               $textfield.closest('tr').remove();
               $textfield.remove();
    }

  }
}

function checkboxChanged()
{
    if($("#checkbox").is(':checked'))
    {
        $(".alertCheckbox").prop('checked', true);
    }else
    {
        $(".alertCheckbox").prop('checked', false);
    }       
}

function deleteChanges(ID)
{
    var matches = [];
    var checkboxes = [];
    $(".alertCheckbox:checked").each(function() {
    matches.push(this.value);
    checkboxes.push(this);
    });
    var tempCheckboxes = JSON.stringify(matches);
    $("#deleteFlags").after('<img src="../design/pictures/loading.gif" width="20px" alt="..." />');
   $.post("ajax/deviceFlagsDelete.php",{flags:tempCheckboxes, deviceID:ID}).done(function(data)
   {
     if(data==="true")
     {
         var count=0;
           for (var i=0;i < checkboxes.length ;i++)
            {
             count++;
             $(checkboxes[i]).closest('tr').fadeTo(400,0,function(){$(this).remove();});
            }  
            if(($(".alertCheckbox").length - count) ===0)
            {
               $(".lastCheckboxElement").each(function() {
                   $(this).closest('tr').fadeTo(400,0,function(){$(this).remove();});
                    });  
               $('#alertTable tr:last').after('<tr><td></td><td>Keine &Auml;nderungen</td></tr>');
            }
            $("#deleteFlags").next('img').remove();
     }
   });    
}

function supplierChange(element, supplierID)
   {
       numberOfBoxes++;
       var submitPar = document.getElementById("submitArea");
       submitPar.innerHTML='<input type="submit" value="Übernehmen" name="submit" />';
       if(oldSupplierID !== null)
       {
           supplierID = oldSupplierID; 
       }
       if(element.value !== supplierID)
       {
           var nameSupplier = null;
           var contactSaleOffice = null;
           var contactService = null; 
           var noteSupplier = null;
           
           $(element).after('<img src="../design/pictures/loading.gif" width="20px" alt="..." />');
           if($('input[name="nameSupplier"]').length > 0)
           {
               nameSupplier = $('input[name="nameSupplier"]').val();
               $(element).children().filter(function() 
               {
                return $(this).val() == supplierID;
               }).text(nameSupplier);
           }
           if($('input[name="contactSaleOffice"]').length > 0)
           {
               contactSaleOffice = $('input[name="contactSaleOffice"]').val();  
           }   
           
           if($('input[name="contactService"]').length > 0)
           {
               contactService= $('input[name="contactService"]').val();  
           }          
           if($('input[name="noteSupplier"]').length > 0)
           {
               noteSupplier = $('input[name="noteSupplier"]').val();  
           }
           
           $.post("ajax/changeSupplier.php",{supplierID:element.value, oldSupplierID:supplierID , nameSupplier:nameSupplier, contactSaleOffice:contactSaleOffice, contactService:contactService, noteSupplier:noteSupplier}).done(function(data)
            {
             if(data==="false")
              {
                 alert(data); 
              }
              var supplierNew = jQuery.parseJSON(data);
                $("#nameSuppliertd").html(supplierNew.name);
                $("#contactSaleOfficetd").html(supplierNew.contactSalesOffice);
                $("#contactServicetd").html(supplierNew.contactService);
                $("#noteSuppliertd").html(supplierNew.note);
                $(element).next('img').remove();
                oldSupplierID = element.value;
            });    
       }
   }

